use axum::{
    Json,
    extract::{Request, State},
    response::IntoResponse,
};
use serde_json::Value;
use tracing::info;

use crate::server::MockState;

pub async fn mock(State(mocker): State<MockState>, request: Request) -> impl IntoResponse {
    let uri = request.uri();
    info!("{uri:?}");
    let path = uri.path();
    let method = request.method();
    for operation in &mocker.document.operations {
        if operation.path.eq(path) {
            if !method.as_str().eq(operation.method.as_str()) {
                return Json(Value::String(format!(
                    "请求方法不匹配，期望：{}，实际：{}",
                    operation.method, method
                )));
            }

            let type_id = operation.response.body.clone().unwrap_or_default();
            let mut current_recursion = 0;
            let value = mocker
                .mocker
                .mock(&type_id, None, &mut current_recursion, &mocker.options);
            return Json(value);
        }
    }
    Json(Value::String(String::from("未匹配到有效的mock路径")))
}

pub async fn doc(State(mocker): State<MockState>) -> impl IntoResponse {
    let document = mocker.document.as_ref().clone();
    Json(document)
}
